<template>
  <div id="distribution_map"></div>
</template>

<script>
import tdTheme from "@/api/ops/echart/theme.json"; // 引入默认主题
import * as mapData from "@/utils/china.json";
import img from '@/assets/login/images/loginBg.jpg'
import {
  provinceRegionCount,
  alarmCountGroupByProvince,
} from "@/api/ops/dashboard";

export default {
  name: "chinaMap",
  data() {
    return {
      options: {},
      map: [],
      myChart: null,
      geoCoord: {
        甘肃: [103.73, 36.03],
        青海: [101.74, 36.56],
        四川: [104.06, 30.67],
        河北: [114.48, 38.03],
        云南: [102.73, 25.04],
        贵州: [106.71, 26.57],
        湖北: [114.31, 30.52],
        河南: [113.65, 34.76],
        山东: [117, 36.65],
        江苏: [118.78, 32.04],
        安徽: [117.27, 31.86],
        浙江: [120.19, 30.26],
        江西: [115.89, 28.68],
        福建: [119.3, 26.08],
        广东: [113.23, 23.16],
        湖南: [113, 28.21],
        海南: [110.35, 20.02],
        辽宁: [123.38, 41.8],
        吉林: [125.35, 43.88],
        黑龙江: [126.63, 45.75],
        山西: [112.53, 37.87],
        陕西: [108.95, 34.27],
        台湾: [121.3, 25.03],
        北京: [116.46, 39.92],
        上海: [121.48, 31.22],
        重庆: [106.54, 29.59],
        天津: [117.2, 39.13],
        内蒙古: [111.65, 40.82],
        广西: [108.33, 22.84],
        西藏: [91.11, 29.97],
        宁夏: [106.27, 38.47],
        新疆: [87.68, 43.77],
        香港: [114.17, 22.28],
        澳门: [113.54, 22.19],
      },
      zoomSize: 1.4, // 地图缩放比例
    };
  },
  props: {
    refreshNum: String,
  },
  watch: {
    refreshNum(val, oldVal) {
      this.alarmCountGroupByProvince();
    },
  },
  mounted() {
    this.$echarts.registerTheme("tdTheme", tdTheme); // 覆盖默认主题
    this.$echarts.registerMap('china', mapData);
    this.init();
    this.provinceRegionCount();
    this.alarmCountGroupByProvince();
    window.addEventListener("resize", this.handleResize);
    // this.$nextTick(() => {
    //   this.init();
    //   // 旋转
    //   this.timer = setInterval(() => {
    //     this.doing();
    //   }, 100);
    // })
  },
  methods: {
    handleResize() {
      // 地图自适应缩放
      this.myChart.resize();
      let domWidth =
        document.body.clientWidth || document.documentElement.clientWidth;
      if (domWidth > 1440) {
        this.zoomSize = 1.6
      } else {
        this.zoomSize = 1.4
      }
    },
    getTooltip() {
      return {
        enterable: true, // 鼠标是否可进入提示框浮层中\
        hideDelay: 200, // 浮层隐藏的延迟
        confine: true,
        position: function (point, params, dom, rect, size) {
          // 提示框位置
          let x = 0; // x坐标位置
          let y = 0; // y坐标位置

          // 当前鼠标位置
          let pointX = point[0];
          let pointY = point[1];

          // 提示框大小
          let boxWidth = size.contentSize[0];
          let boxHeight = size.contentSize[1];

          if (boxWidth > pointX) {
            x = 5; // 自己定个x坐标值，以防出屏
            y -= 15; // 防止点被覆盖住，可根据情况自行调节
          } else {
            // 左边放的下
            x = pointX - boxWidth - 15;
          }

          if (boxHeight + 20 > pointY) {
            y = pointY + 15;
          } else if (boxHeight > pointY) {
            y = 5;
          } else {
            // 上边放得下
            y += pointY - boxHeight;
          }
          return [point[0] - boxWidth - 20, point[1] - 30];
        },

        backgroundColor: "rgba(255, 255, 255, 0.7)",
        padding: [15, 15, 15, 15],

        formatter: (params) => {
          let sumaryAmount, sumaryCnt, userCnt;
          var htmlStr = "";
          if (this.mapList) {
            let list = this.mapList;
            let dataList = list.filter(item => {
              return item.name === params.name //判断返回数据的name和实际散点的name相同
            })
            if (dataList.length > 0) {
              sumaryAmount = dataList[0].amount;
              sumaryCnt = dataList[0].count;
              userCnt = dataList[0].traderCount;
              htmlStr = `<div class="tooltip-style" style="position:relative;">
                          <span style="margin-bottom: 10px;color: #0081CC;font-size:20px;font-weight:600;padding-top: 0">${params.name}</span><br />
                          <div style="line-height:30px;margin-top:10px">
                          <span style="color: #333;font-size:14px">融资金额（万元）:  ${sumaryAmount ? sumaryAmount : ''}</span><br />
                          <span style="color: #333;font-size:14px">融资笔数（笔）:  ${sumaryCnt ? sumaryCnt : ''}</span><br />
                          <span style="color: #333;font-size:14px">融资笔数（人）:  ${userCnt ? userCnt : ''}</span><br />
                          </div>
                        </div>`;
            }
            return htmlStr;
          }
        },

        extraCssText: "box-shadow: 4px 6px 25px 0px rgba(163, 177, 190, 0.4), inset 0px 0px 2px 0px #FFFFFF; backdropFilter: blur(4px);border-radius:12px;width:auto;",
        textStyle: {
          fontSize: 16,
          color: "#fff",
        },
      }
    },
    getGeo() {
      //这里设置为地图的阴影
      return [{ // 这个是重点 —— 这里设置为地图的阴影
        map: 'china',
        roam: false, // 禁止拖拽
        silent: true, // 禁止hover效果
        zoom: this.zoomSize, // 地图比例
        center: [105.194115019531, 36.582111640625], // 地图中心位置， 此处的纬度与下面的center相差1度是形成阴影的距离，可自己随意调整
        itemStyle: {
          normal: {
            borderColor: 'transparent',
            areaColor: "rgb(1,42,170)",
          },
        },
        regions: [{
          name: "南海诸岛",
          itemStyle: {
            // 隐藏地图
            normal: {
              opacity: 0, // 为 0 时不绘制该图形
            }
          },
          label: {
            show: false // 隐藏文字
          }
        }],
      }]
    },
    // 此处为真正的地图
    getSeries() {
      let series = [{
        name: "", // 浮动框的标题
        type: "map",
        map: "china",
        aspectScale: 0.75,
        zoom: this.zoomSize,
        layoutSize: "100%",
        roam: false,
        label: {
          normal: {
            show: false, //显示省份标签
            textStyle: { color: "#efefef" }, //省份标签字体颜色
          },
          emphasis: {
            //对应的鼠标悬浮效果
            show: true,
            textStyle: { color: "#fff" },
          },
        },
        emphasis: {
          // 鼠标hover是否显示内容，
          label: {
            //用于显示地图文本内容
            show: true,
            textStyle: {
              color: "#fff",
            },
          },
        },
        center: [105.194115019531, 35.582111640625], // 设置地图中心
        //     itemStyle: {
        //       normal: {
        //         color: "red",
        //         areaColor: "rgba(19,54,162, .5)",
        //         borderColor: "rgba(0,242,252,.3)",
        //         borderWidth: 1,
        //         shadowBlur: 7,
        //         shadowColor: "#00f2fc",
        //       },
        //       emphasis: {
        //         areaColor: "#4f7fff",
        //         borderColor: "rgba(0,242,252,.6)",
        //         borderWidth: 2,
        //         shadowBlur: 10,
        //         shadowColor: "#00f2fc",
        //       },
        //     },
        //   },
        itemStyle: {
          // 地图的样式
          normal: {
            borderColor: "rgba(74,133,203)", // 省份边框颜色
            areaColor: {
              image: img,  // 背景图
              repeat: 'repeat-x',
              global: false, // 缺省为 false
            },
            borderWidth: 1, // 省份边框宽度
            shadowColor: "rgba(255,255,255,0.2)", // 省份边框阴影
            shadowBlur: 5, // 省份边框聚焦
          },
          emphasis: {
            // 鼠标hover显示
            show: false,
            //areaColor: "#0D30D4",
            areaColor: {
              type: "linear",
              x: 1,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [{
                offset: 0,
                color: "rgb(243,135,36)", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "rgb(218,172,113)", // 100% 处的颜色
              },
              ],
              global: false, // 缺省为 false
            },
            color: "#fff",
            // textStyle: {
            //   color: "#fff",
            // },
          },
        },
        // data: this.mapList,
      },
      {
        type: "effectScatter",
        coordinateSystem: "geo",
        showEffectOn: "render",
        symbolSize: 20,
        zlevel: 1,
        rippleEffect: {//涟漪特效相关配置
          brushType: 'stroke'
        },
        label: {//图形上的文本标签，可用于说明图形的一些数据信息，比如值，名称等
          show: true,
          position: 'right',
          formatter: '{b}'
        },
        // symbolSize: function (val) {//标记的大小
        //   return val[2] / 8;
        // },
        itemStyle: {
          //圆点的颜色
          color: '#46bee9'
        },
      }, {
        type: 'pie',
        // coordinateSystem: 'geo',
        zlevel: 1,
        silent: true, //图形是否不响应和触发鼠标事件，默认为 false，即响应和触发鼠标事件
        startAngle: 0,
        radius: ['8%', '12%'],
        label: { show: false },
        labelLine: { show: false },
        data: [
          { value: 100, name: 'B1', itemStyle: { color: '#46bee9', borderWidth: 0, borderColor: '#46bee9', }, },
          { value: 20, name: 'B2', itemStyle: { color: '#ffffff00', borderWidth: 0, borderColor: '#ffffff00', }, },
          { value: 100, name: 'B3', itemStyle: { color: '#46bee9', borderWidth: 0, borderColor: '#46bee9', }, },
          { value: 20, name: 'B4', itemStyle: { color: '#ffffff00', borderWidth: 0, borderColor: '#ffffff00', }, },
          { value: 100, name: 'B5', itemStyle: { color: '#46bee9', borderWidth: 0, borderColor: '#46bee9', }, },
          { value: 20, name: 'B6', itemStyle: { color: '#ffffff00', borderWidth: 0, borderColor: '#ffffff00', }, },
        ],
        animation: false, //是否开启动画
      }]
      return series;
    },
    doing() {
      if (this.options.series) {
        this.options.series[2].startAngle = this.options.series[2].startAngle - 20;
        // this.options.series[2].startAngle = this.options.series[2].startAngle - 5;
        this.myChart.setOption(this.options);
      }
    },
    provinceRegionCount() {
      let $this = this;
      provinceRegionCount().then((response) => {
        if (response.code == 0 && response.data != null) {
          for (let x in response.data) {
            if (
              response.data[x].province.startsWith("内蒙古") ||
              response.data[x].province.startsWith("黑龙江")
            ) {
              let item = {
                name: response.data[x].province.substring(0, 3),
                value: response.data[x].count,
              };
              $this.map.push(item);
            } else {
              let item = {
                name: response.data[x].province.substring(0, 2),
                value: response.data[x].count,
              };
              $this.map.push(item);
            }
          }
          $this.options.series[0].data = $this.map;
          $this.myChart.setOption($this.options);
        }
      });
    },
    alarmCountGroupByProvince() {
      let $this = this;
      alarmCountGroupByProvince().then((response) => {
        if (response.code == 0 && response.data != null) {
          let data = [];
          for (let x in response.data) {
            let province = response.data[x]["province"] || '';
            if (
              province.startsWith("内蒙古") ||
              province.startsWith("黑龙江")
            ) {
              province = province.substring(0, 3);
            }
            province = province.substring(0, 2);
            let color = "greenyellow";
            if (response.data[x]["level"] == 2) {
              color = "orangered";
            }
            let values = this.geoCoord[province] || [];
            if (values.length < 3) {
              values.push(response.data[x]["count"]);
            } else {
              values[2] = response.data[x]["count"];
            }
            let item = {
              name: province,
              value: values,
              itemStyle: { color: color },
            };
            data.push(item);
          }
          $this.options.series[1].data = data;
          $this.myChart.setOption($this.options);
        }
      });
    },
    init() {
      let worldMapContainer1 = document.getElementById("distribution_map");
      this.myChart = this.$echarts.init(worldMapContainer1, "tdTheme");
      this.options = {
        tooltip: {
          formatter: function (params) {
            if (params.seriesType == "map") {
              if (params.data) {
                return params.data.name + "<br/>项目数量：" + params.data.value;
              }
            } else {
              return (
                params.data.name + "<br/>告警总数：" + params.data.value[2]
              );
            }
          },
        },
        legend: {
          orient: "vertical",
          x: "left",
          y: "bottom",
          data: ["已安装设备"],
          textStyle: {
            color: "#ccc",
          },
        },
        geo: this.getGeo(),
        series: this.getSeries()

      };
      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption(this.options);
      // this.myChart.on("click", function (params) {
      //   //点击事件
      //   if (params.componentType === "series") {
      //   }
      // });
    },
  },
};
</script>

<style scoped>
#distribution_map {
  /* height: 7rem; */
  height: 100%;
  width: 100%;
  padding: 10px;
}
</style>
